from database import db
from errors import Missing

from data.models import Parking


def create_parking_json(
    address: str, opened: bool, count_places: int, count_available_places: int
) -> dict:
    parking = Parking(
        address=address,
        opened=opened,
        count_places=count_places,
        count_available_places=count_available_places,
    )
    db.session.add(parking)
    db.session.commit()
    return parking.to_json()


def _get_parking(parking_id: int) -> Parking:
    parking = db.session.query(Parking).where(Parking.id == parking_id).scalar()

    if parking:
        return parking

    raise Missing(msg=f"Parking with id={parking_id} does not exist")


def get_parking_json(parking_id: int) -> dict:
    return _get_parking(parking_id).to_json()


def _update_parking(
    parking_id: int,
    address: str,
    opened: bool,
    count_places: int,
    count_available_places: int,
) -> Parking:
    parking = _get_parking(parking_id)

    parking.address = address
    parking.opened = opened
    parking.count_places = count_places
    parking.count_available_places = count_available_places

    db.session.commit()

    return parking


def update_parking_json(
    parking_id: int,
    address: str,
    opened: bool,
    count_places: int,
    count_available_places: int,
) -> dict:
    updated = _update_parking(
        parking_id, address, opened, count_places, count_available_places
    )
    return updated.to_json()
